package shape

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gitee.com/git_public/vfaith/sugar"
	"gitee.com/git_public/vfaith/sugar/regexpv"
	"strings"
	"time"
)

type CusTime struct {
	*time.Time
}

func NewCusNow() *CusTime {
	now := time.Now()
	return &CusTime{Time: &now}
}

func NewCusTime(str string) *CusTime {
	if str == "" {
		return &CusTime{Time: nil}
	}
	if regexpv.DateRegExp(str) {
		str = str + " 00:00:00"
	}
	parsedTime, err := sugar.StringToTime(str) // 根据需要定义时间格式
	if err != nil {
		return nil
	}
	return &CusTime{Time: parsedTime}
}

func (ct *CusTime) MarshalJSON() ([]byte, error) {
	//time.ParseInLocation(ct.Time, str, time.Local)
	timeStr := sugar.FormatTimeToDateTime(*ct.Time)
	return json.Marshal(timeStr)
}

// UnmarshalJSON 方法实现，来解析自定义格式的时间
func (ct *CusTime) UnmarshalJSON(b []byte) (err error) {
	str := strings.Trim(string(b), `"`)
	if len(str) == 0 {
		return nil
	}

	ct.Time, err = sugar.StringToTime(str)
	return err
}

// Scan 实现 sql.Scanner 接口
func (ct *CusTime) Scan(value interface{}) error {
	if v, ok := value.(time.Time); ok {
		*ct = CusTime{Time: &v}
		return nil
	}
	return fmt.Errorf("unsupported scan type %T, expected time.Time", value)
}

// Value 实现 driver.Valuer 接口
func (ct *CusTime) Value() (driver.Value, error) {
	if ct == nil || ct.Time == nil {
		return nil, nil
	}
	return *ct.Time, nil
}
